#!/usr/bin/env python3
#coding:utf-8

__author__ = 'xmxoxo<xmxoxo@qq.com>'

import cv2
import numpy as np
import math

# 逆时针旋转
def Nrotate(angle,valuex,valuey,pointx,pointy):
    angle = (angle/180)*math.pi
    valuex = np.array(valuex)
    valuey = np.array(valuey)
    nRotatex = (valuex-pointx)*math.cos(angle) - (valuey-pointy)*math.sin(angle) + pointx
    nRotatey = (valuex-pointx)*math.sin(angle) + (valuey-pointy)*math.cos(angle) + pointy
    return (nRotatex, nRotatey)

# 顺时针旋转
def Srotate(angle,valuex,valuey,pointx,pointy):
    angle = (angle/180)*math.pi
    valuex = np.array(valuex)
    valuey = np.array(valuey)
    sRotatex = (valuex-pointx)*math.cos(angle) + (valuey-pointy)*math.sin(angle) + pointx
    sRotatey = (valuey-pointy)*math.cos(angle) - (valuex-pointx)*math.sin(angle) + pointy
    return (sRotatex,sRotatey)

# 将四个点做映射
def rotatecordiate(angle, rectboxs, pointx, pointy):
    output = []
    for rectbox in rectboxs:
        if angle>0:
            output.append(Srotate(angle,rectbox[0],rectbox[1],pointx,pointy))
        else:
            output.append(Nrotate(-angle,rectbox[0],rectbox[1],pointx,pointy))
    return output

# 图像裁剪
def image_crop(image, box):
      xs = [x[1] for x in box]
      ys = [x[0] for x in box]
      cropimage = image[min(xs):max(xs),min(ys):max(ys)]
      return cropimage

def cut_points(rotateimg, contours, scale=1.1):
    ''' 旋转并切出子图
    '''
    contours = np.array(contours, dtype=np.int32)
    rect = cv2.minAreaRect(contours)
    # rect为[(旋转中心x坐标，旋转中心y坐标),(矩形长，矩形宽), 旋转角度]
    print('rect:', rect)
    rect = list(rect)
    if scale != 1:
        # 高度变大1.1倍
        rect[1] = (rect[1][0] * scale, rect[1][1]*scale)
        rect = tuple(rect)
        print('scale rect:', rect)

    box_origin = cv2.boxPoints(rect) #box_origin为[(x0,y0),(x1,y1),(x2,y2),(x3,y3)]
    box = rotatecordiate(rect[2], box_origin, rect[0][0], rect[0][1])

    angle = rect[2]
    # print('angle:%f'%angle)
    if 90>=angle>=45: angle = angle-90
    M = cv2.getRotationMatrix2D(rect[0], angle, 1)
    dst = cv2.warpAffine(rotateimg, M, (2*rotateimg.shape[0], 2*rotateimg.shape[1]))

    ret = image_crop(dst, np.int0(box))
    return ret

if __name__ == '__main__':
    pass

